package com.phenix.mvp.api;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.orhanobut.logger.Logger;
import com.phenix.mvp.App;
import com.phenix.mvp.util.NetWorkUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

/**@author zhouphenix
 * addNetworkInterceptor添加的是网络拦截器，他会在在request和resposne是分别被调用一次，
 * addinterceptor添加的是aplication拦截器，他只会在response被调用一次
 */
public final class Api {
    /**BASE_URL*/
    public static final String BASE_URL = "http://192.168.1.4:8000/phenix/";
    /**有服务器端生成进行app验证，暂时作为移动端和pc端的区别*/
    public static final String X_APP_ID = "454896c67cb84bc326514715b4a529dd";
    /**KEY*/
    public static final String X_APP_KEY = "454896c67cb84bc326514715b4a529dd";

    /**ApiService*/
    public ApiService service;

    /**添加网络id拦截器*/
    private Interceptor mInterceptor = (chain) -> chain.proceed(chain.request().newBuilder()
            .addHeader("X_APP_ID", X_APP_ID)
            .addHeader("X_APP_KEY", X_APP_KEY)
            .addHeader("Content-Type", "application/json")
            .build());

    private Api(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        File cacheFile = new File(App.getAppContext().getCacheDir(), "cache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb

        OkHttpClient client =  new OkHttpClient.Builder()
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .addInterceptor(mInterceptor)
                .addInterceptor(httpLoggingInterceptor)
                .addNetworkInterceptor(new HttpCacheInterceptor())
                .cache(cache)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        service = retrofit.create(ApiService.class);
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        /**懒汉模式构造实例*/
        private static final Api INSTANCE = new Api();
    }

    //获取单例
    public static Api getInstance() {
        return SingletonHolder.INSTANCE;
    }
    class HttpCacheInterceptor implements Interceptor {//连接到服务器才工作

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetWorkUtil.isNetConnected(App.getAppContext())) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
                Logger.t("HttpCacheInterceptor").d("No Network");
            }
            Response originalResponse = chain.proceed(request);
//            String token = originalResponse.header("Set-Cookie");
            if (NetWorkUtil.isNetConnected(App.getAppContext())) {
                //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            }
            else {
                final int maxTime = 1*24*60*60;
                return originalResponse.newBuilder()
                        //这里的设置的是我们的没有网络的缓存时间，想设置多少就是多少。
                        .header("Cache-Control", "public, only-if-cached, max-stale="+maxTime)
                        .removeHeader("Pragma")
                        .build();
            }
        }
    }

}
